<script setup>
    import { ref, onBeforeUnmount } from 'vue'
    import request from "../../../common/utils/request";
    import utils from '../../../common/utils/utils'
    import QRCode from 'qrcode'

    const props = defineProps({
        appId: {
            type: Number,
            required: true,
        }
    })
    const emit = defineEmits(['authed'])

    const loading = ref(false)
    const qrImage = ref('')
    const timer = ref(null)

    let clearRefreshInterval = () => {}

    const initState = () => {
        qrImage.value = ''

        clearInterval(timer.value)
        timer.value = null

        clearRefreshInterval()
    }

    const getQrImage = () => {
        loading.value = true

        request.post('work_ai', '/api/qy_wechat/auth/qrcode', { app_id: props.appId }).then(async ({data: {qrcode_url}}) => {
            qrImage.value = await QRCode.toDataURL(qrcode_url) 
            loading.value = false
            
            //定时查看有没有授权
            scanSceneLogin()

            //两分钟后刷新二维码
            clearRefreshInterval = utils.refreshWithInterval(2, 2, () => {
                initState()
                getQrImage()
            })
        })
    }

    const scanSceneLogin = () => {
        timer.value = setInterval(() => {
            request.get('work_ai', '/api/qy_wechat/auth/scan', { app_id: props.appId }).then(({data}) => {
                if (data.status === 1) {
                    initState()
                    emit('authed')
                }
            })
        }, 1000)
    }

    getQrImage()

    onBeforeUnmount(() => {
        initState()
    })
</script>

<template>
    <div class="qr-image">
        <a-spin :spinning="loading">
            <img :src="qrImage" v-if="qrImage"/>
        </a-spin>
    </div>
</template>

<style lang="less" scoped>
    .qr-image {
        width: 170px;
        height: 170px;
        display: flex;
        justify-content: center;
        align-items: center;
        border: 1px solid #d9d9d9;
        border-radius: 6px;

        img {
            width: 165px;
            height: 165px;
        }
    }
</style>